package com.roin.learn.activiti.controller;

import com.roin.learn.activiti.base.BaseController;
import com.roin.learn.activiti.base.SysConstent;
import com.roin.learn.activiti.entity.User;
import com.roin.learn.activiti.exception.BusinessException;
import com.roin.learn.activiti.service.ProcessService;
import com.roin.learn.activiti.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController extends BaseController{
    @Resource
    UserService userService;
    @Resource
    ProcessService processService;

    @RequestMapping("/login.do")
    public String login(@RequestParam(required = true) String userId, String pwd, HttpSession session, Model model){
        try {
            User user = userService.getByUserId(userId);
            if (user==null)
                throw new BusinessException("用户名不存在！");
            if (!pwd.equals(user.getUserPassword()))
                throw new BusinessException("用户名或密码不正确！");

            try {
                int personalTaskCount = processService.queryAssigneeTaskCount(user.getUserId());
                user.setTaskCount(personalTaskCount);
            } catch (Exception e) {
                log.error("登录时查询用户任务数量异常",e);
            }
            session.setAttribute(SysConstent.SESSION_LOGIN_USER_KEY,user);
            return "redirect:/";
        } catch (BusinessException e) {
            model.addAttribute("error",e.getMessage());
        } catch (Exception e) {
            model.addAttribute("error","登录异常");
            log.error("登录异常",e);
        }
        model.addAttribute("userId",userId);
        model.addAttribute("pwd",pwd);
        return "login";
    }
    @RequestMapping("/login.htm")
    public String toLogin(){
        return "login";
    }
    @RequestMapping("/logout.do")
    public String logout(HttpSession session ){
        session.removeAttribute(SysConstent.SESSION_LOGIN_USER_KEY);
        return "redirect:/login.htm";
    }
}
